package com.example.hxds.common.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.hxds.common.exception.HxdsException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @BelongsProject: hxds
 * @BelongsPackage: com.example.hxds.common.util
 * @Author: caohaoran
 * @CreateTime: 2025-10-18  16:45
 * @Description: TODO
 * @Version: 1.0
 */
@Component("MicroAppUtil")
public class MicroAppUtil {

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    public String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        //前端通过微信登录接口获取的临时code(有效期约为五分钟)
        map.put("js_code", code);
        //固定值authorization_code,表示授权类型。
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openid = json.getStr("openid");
        if(openid==null || openid.length()==0){
            throw new RuntimeException("临时登录凭证错误");
        }
        return openid;
    }

    public String getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        HashMap map = new HashMap(){{
            //固定值client_credential，表示采用客户端凭证方式获取access_token
            put("grant_type","client_credential");
            put("appid", appId);
            put("secret", appSecret);
        }};
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        if (json.containsKey("access_token")) {
            String accessToken = json.getStr("access_token");
            return accessToken;
        }else {
            throw new HxdsException(json.getStr("errmsg"));
        }
    }
}
